import { Article, Channel } from '@/types/data'
import { RootAction } from '@/types/store'

type InitType = {
  userChannels: Channel[]
  allChannels: Channel[]
  activeId: number
  channelActicles: {
    [key: number]: {
      timestamp: string
      articles: Article[]
    }
  }
}

const initValue: InitType = {
  userChannels: [], // 用户自己的频道
  allChannels: [], // 所有频道
  activeId: -1, // 高亮项的id
  channelActicles: {},
}

export default function homeReducer(
  state: InitType = initValue,
  action: RootAction
): InitType {
  // { type: 'home/set_user_channels', payload: xxxx }
  if (action.type === 'home/set_user_channels') {
    return {
      ...state,
      userChannels: action.payload,
    }
  }
  if (action.type === 'home/set_all_channels') {
    return {
      ...state,
      allChannels: action.payload,
    }
  }

  // { type: 'home/set_active_id', payload: 8 }
  if (action.type === 'home/set_active_id') {
    return {
      ...state,
      activeId: action.payload,
    }
  }

  // { type: 'home/set_channel_articles', payload: { timestamp:xx ,channel_id: xxx, articles: xx } }
  if (action.type === 'home/set_channel_articles') {
    const { channel_id, timestamp, articles } = action.payload

    // h5网页是没有分页的效果，上拉加载，数据是追加式的，数据是越来越多的！！需要合并老数据
    const oldArticles = state.channelActicles[channel_id]?.articles || []

    return {
      ...state,
      channelActicles: {
        ...state.channelActicles,
        [channel_id]: {
          timestamp: timestamp,
          articles: [...oldArticles, ...articles],
        },
      },
    }
  }

  if (action.type === 'home/refresh_channel_articles') {
    const { channel_id, timestamp, articles } = action.payload

    return {
      ...state,
      channelActicles: {
        ...state.channelActicles,
        [channel_id]: {
          timestamp,
          articles,
        },
      },
    }
  }

  return state
}
